<template>
  <div class="purchase-paln-wrap table-gl-w">
    <a-tabs @change="changeStatus" v-model:active-key="currentTab" size="mini">
      <a-tab-pane v-for="tab in tabsList" :key="tab.key">
        <template #title>
          <span>{{ tab.title }}</span>
          <span v-if="tab.key">({{ countMap[tab.key] || 0 }})</span>
        </template>
      </a-tab-pane>
    </a-tabs>
    <div class="search-w table-filter-form">
      <FilterTable :filterItem="filterItem" :isReset="true" @search="searchByVal" />
    </div>
    <div class="table-gl-con">
      <TableWrap style="flex: 1" @refresh="getTableList">
        <template #tableBody>
          <a-table class="table-singe-line" ref="tableListref" :span-method="spanMethodAll" row-key="id" :expandable="expandable" :default-expand-all-rows="true" :loading="tableLoading" @selection-change="selectColumn" :row-selection="rowSelection" :columns="tableColumns" :data="tableList" size="mini" :pagination="false" :scroll="{ y: '100%' }">
            <template #columns>
              <a-table-column v-for="(item, index) of tableColumns" :fixed="item.fixed" :key="index" :align="item.align" :width="item.width" :title="item.title" :data-index="item.dataIndex">
                <template #title v-if="item.tip">
                  <a-popover>
                    <template #content>
                      <p v-for="(str, i) in item.tip.split('--')" :key="i" style="max-width: 500px">{{ str }}</p>
                    </template>
                    <p>
                      <span>{{ item.title }}</span>
                      <icon-question-circle />
                    </p>
                  </a-popover>
                </template>
                <template v-if="item.dataIndex == 'sort'" #cell="{ rowIndex }">
                  <p>{{ rowIndex + 1 }}</p>
                </template>
                <template v-else-if="item.dataIndex == 'img'" #cell="{ record }">
                  <div class="flex-c-sb" style="padding-right: 20px; max-width: 100%">
                    <div class="order-w flex">
                      <div class="order-detail-item" style="width: 250px" @click="openInStorageDetail(record)">
                        <div class="flex-c">
                          <span class="label">收货仓：</span>
                          <TextLimit style="flex: 1" :val="`${record.warehouseName}(${record.warehouseCode})`" :rows="1" />
                        </div>
                        <div class="flex-c">
                          <span class="label">入库单号：</span>
                          <span class="highlight cursor">{{ record.billNo }}</span>
                          <CopyText class="popup-edit-icon-hover" style="margin-left: 5px" :val="record.billNo" />
                        </div>
                      </div>
                      <div class="order-detail-item" style="width: 250px">
                        <p><span class="label">申购方：</span>{{ record.companyName }}</p>
                        <p><span class="label">采购方：</span>{{ record.purchaseOrgName }}</p>
                      </div>
                      <div class="order-detail-item" style="width: 180px">
                        <p><span class="label">入库数量：</span>{{ record.skuType }}SKU，{{ record.status == 30 ? record.warehouseRealAmt : record.warehouseAmt }}件</p>
                        <p><span class="label">合计金额：</span>￥{{ record.totalAmount }}</p>
                      </div>
                      <div class="order-detail-item" v-if="currentTab == 10" style="width: 200px">
                        <p><span class="label">提交时间：</span>{{ $setTime(record.gmtCreate, 'YYYY/MM/DD HH:mm') }}</p>
                      </div>
                      <div class="order-detail-item" v-if="currentTab == 30" style="width: 200px">
                        <p><span class="label">签收人：</span>{{ record.warehouseUname }}</p>
                        <p><span class="label">签收时间：</span>{{ $setTime(record.gmtFinished, 'YYYY/MM/DD HH:mm') }}</p>
                      </div>
                      <div class="order-detail-item" v-if="currentTab == 20" style="width: 200px">
                        <p><span class="label">拒收人：</span>{{ record.warehouseUname }}</p>
                        <p><span class="label">拒收时间：</span>{{ $setTime(record.gmtRefuse, 'YYYY/MM/DD HH:mm') }}</p>
                      </div>
                      <div class="order-detail-item" v-if="currentTab == 20 || currentTab == 30" style="width: 200px">
                        <div class="flex-c">
                          <span class="label">备注：</span>
                          <TextLimit style="flex: 1" :val="record.remark" :row="1" />
                        </div>
                        <div class="flex-c warningColor" v-if="currentTab == 20">
                          <span class="label">拒收：</span>
                          <TextLimit class="warningColor" style="flex: 1" :val="record.refuseMsg" />
                        </div>
                      </div>
                    </div>
                  </div>
                </template>
              </a-table-column>
            </template>
            <template #expand-row="{ record }">
              <a-table class="table-singe-line show-border-table" row-class="child-row" :show-header="false" row-key="id" :bordered="false" :columns="tableColumns" :data="record.billItems" size="mini" :pagination="false">
                <template #columns>
                  <a-table-column :width="10" />
                  <a-table-column :width="40" />
                  <a-table-column v-for="(item, index) of tableColumns" :key="index" :fixed="item.fixed" :align="item.align" :width="item.width" :title="item.title" :data-index="item.dataIndex">
                    <template v-if="item.dataIndex == 'sort'" #cell> </template>
                    <template v-else-if="item.dataIndex == 'img'" #cell="option">
                      <ImgPopover :src="option.record.productImg">
                        <template #con>
                          <a-image width="40" height="40" fit="contain" :src="option.record.productImg" />
                        </template>
                      </ImgPopover>
                    </template>
                    <template v-else-if="item.dataIndex == 'sku'" #cell="option">
                      <TextLimit class="highlight cursor" :val="option.record.sku" @click="openInStorageItemDetail(option.record, record)" />
                    </template>
                    <template v-else-if="item.dataIndex == 'productSpecs'" #cell="option">
                      <TextLimit :val="getProductSpecs(option.record)" />
                    </template>
                    <template v-else-if="item.dataIndex == 'props'" #cell="option">
                      <template v-if="option.record.purchaseSpecsArr && option.record.purchaseSpecsArr.length">
                        <PurchasePropPopover :purchaseSpecsArr="option.record.purchaseSpecsArr" />
                      </template>
                    </template>
                    <template v-else-if="item.dataIndex == 'rate'" #cell="option">
                      <p>{{ option.record.rate }}%</p>
                      <p class="price-type highlight">{{ option.record.priceType === 1 ? '含税' : '不含税' }}</p>
                    </template>
                    <template v-else-if="item.dataIndex == 'planNo'" #cell="option">
                      <p class="highlight">{{ option.record.planNo }}</p>
                    </template>
                    <template v-else-if="item.dataIndex == 'warehouseAmt'" #cell="option">
                      <p v-if="record.status != 30">{{ option.record.warehouseAmt }}</p>
                      <p v-else>{{ option.record.warehouseRealAmt }}</p>
                    </template>
                    <template v-else-if="item.dataIndex == 'materialWeight'" #cell="option">
                      <p v-if="record.status != 30">{{ option.record.materialWeight }}</p>
                      <p v-else>{{ option.record.materialRealWeight }}</p>
                    </template>
                    <template v-else-if="['materialPrice', 'productPrice', 'laborPrice', 'materialAmount', 'productAmount', 'laborAmount', 'otherAmount', 'totalAmount', 'taxAmount', 'singleAmount'].includes(item.dataIndex)" #cell="option">
                      <p>￥{{ option.record[item.dataIndex] }}</p>
                    </template>
                  </a-table-column>
                </template>
              </a-table>
            </template>
          </a-table>
        </template>
      </TableWrap>
      <div class="pagination-footer">
        <a-pagination size="mini" :total="total" :default-page-size="searchVal.pageSize" :current="searchVal.pageNum" :page-size-options="[20, 50, 100, 200, 500]" show-total show-page-size @page-size-change="sizeChange" @change="changePage" />
      </div>
    </div>
  </div>
  <!-- 入库单详情 -->
  <ApplicationInStorageDetail v-if="showInStorageDetail" :isShow="showInStorageDetail" source="purchaser" :currentId="currentData.id" @closed="showInStorageDetail = false" />
  <!-- 入库明细详情 -->
  <ApplicationInStorageItemDetail v-if="showInStorageItemDetail" :isShow="showInStorageItemDetail" source="purchaser" :currentItem="currentData" @closed="showInStorageItemDetail = false" />
</template>
<script lang="ts" setup>
  import { ref, onMounted } from 'vue'
  import { FilterTableItem } from '@/types/components'
  import FilterTable from '@/components/TableFilter.vue'
  import ApplicationInStorageDetail from '../components/applicationInStorageDetail.vue'
  import ApplicationInStorageItemDetail from '../components/applicationInStorageItemDetail.vue'
  import { findReceiptPage, findReceiptCountStatus } from '@/api/purchaseApplication'
  import useBaseDataStore from '@/store/modules/base-data'
  import { parseJson } from '@/utils'
  import PurchasePropPopover from '../components/purchasePropPopover.vue'
  import { findSaasAndErpWarehouse } from '@/api/warehouse'

  onMounted(async () => {
    getWareHouseList()
    getUserList()
    getListAndCount()
    getDeptList()
  })
  const filterItem = ref<Array<FilterTableItem>>([
    {
      type: 'input_keyword',
      key: 'billNos',
      keyItems: [{ label: '单号', value: 'billNos' }],
      keyWidth: '70',
      value: ref(),
      placeholder: '请输入',
      label: '',
      width: 160,
      isMultiple: true,
    },
    {
      type: 'input_keyword',
      key: 'skus',
      keyItems: [{ label: 'SKU', value: 'skus' }],
      keyWidth: '70',
      value: ref(),
      placeholder: '请输入',
      label: '',
      width: 160,
      isMultiple: true,
    },
    {
      key: 'warehouseCode',
      label: '收货仓库',
      value: ref(),
      type: 'select',
      width: 120,
      optionItems: [],
    },
    {
      key: 'salesmanIds',
      label: '申购人',
      value: ref(),
      type: 'select_multiple',
      width: 120,
      optionItems: [],
    },
    {
      key: 'productType',
      label: '采购类型',
      value: ref(),
      type: 'select',
      width: 110,
      optionItems: [
        { label: '普货', value: 1 },
        { label: '样品', value: 2 },
      ],
    },
    {
      key: 'purchaseOrgIds',
      label: '采购公司',
      placeholder: '采购公司',
      value: ref(),
      type: 'cascader1',
      width: 160,
      optionItems: [],
      attrs: {
        checkStrictly: true,
        fieldNames: { value: 'id', label: 'deptName' },
        placeholder: '采购公司',
        multiple: true,
        formatLabel: (options: any) => {
          const labels = options.map((option: any) => option.deptName)
          return labels?.[labels.length - 1]
        },
      },
    },
    {
      type: 'keyword_date_range',
      key: 'gmtCreate',
      keyItems: [
        { label: '创建日期', value: 'gmtCreate' },
        { label: '签收时间', value: 'gmtFinished' },
        { label: '拒收时间', value: 'gmtRefuse' },
      ],
      keyWidth: '130',
      value: ref(),
      placeholder: '请输入',
      label: '创建时间',
      width: 240,
      attrs: {
        valueFormat: 'YYYY-MM-DD HH:mm:ss',
        timePickerProps: { defaultValue: ['00:00:00', '23:59:59'] },
      },
    },
  ])
  const tableColumns: Array<any> = [
    {
      title: '序号',
      dataIndex: 'sort',
      width: 40,
    },
    {
      title: '图片',
      dataIndex: 'img',
      width: 60,
    },
    {
      title: 'SKU',
      dataIndex: 'sku',
      width: 100,
    },
    {
      title: '规格',
      dataIndex: 'productSpecs',
      width: 100,
    },
    {
      title: '采购参数',
      dataIndex: 'props',
      width: 140,
    },
    {
      title: '申购人',
      dataIndex: 'salesmanName',
      width: 70,
    },
    {
      title: '采购员',
      dataIndex: 'purchaseUname',
      width: 70,
    },

    {
      title: '店铺',
      dataIndex: 'shopName',
      width: 80,
    },

    {
      title: '入库数量',
      dataIndex: 'warehouseAmt',
      width: 70,
    },
    {
      title: '入库材质重量(g)',
      dataIndex: 'materialWeight',
      tip: '金银等贵金属首饰类产品是按材质重量计算价格的，所以入库时必须要有材质重量',
      width: 80,
    },
    {
      title: '材质单价(元/g)',
      dataIndex: 'materialPrice',
      width: 80,
    },
    {
      title: '产品单价',
      dataIndex: 'productPrice',
      width: 80,
      tip: '产品单价：单个产品的成本价，默认值从该申购单关联的采购单上获取',
    },
    {
      title: '工费单价',
      dataIndex: 'laborPrice',
      width: 80,
      tip: '工费是指采购人员的服务费。--固定值：提交申购的时候确认的固定价格。--固定值：固定单价默认获取工费报价表，或者从最近一次申购单获取。--产品单价比列：根据入库单上的产品单价按百分比计算工费。',
    },
    {
      title: '材质金额',
      dataIndex: 'materialAmount',
      tip: '材质金额=材质单价*入库材质重',
      width: 80,
    },
    {
      title: '产品金额',
      dataIndex: 'productAmount',
      tip: '产品金额=产品单价*入库数量',
      width: 80,
    },
    {
      title: '工费',
      dataIndex: 'laborAmount',
      tip: '工费=工费单价*入库数量',
      width: 80,
    },
    {
      title: '其他费用',
      dataIndex: 'otherAmount',
      width: 80,
      tip: '其他费用：本次采购入库产生的其他费用',
    },
    {
      title: '合计金额',
      dataIndex: 'totalAmount',
      width: 80,
      tip: '合计金额=材质金额+产品接你+其他费用+工费',
    },
    {
      title: '税率',
      dataIndex: 'rate',
      width: 60,
    },
    {
      title: '税金',
      dataIndex: 'taxAmount',
      tip: '税金=合计金额*税率',
      width: 80,
    },
    {
      title: '单件货值',
      dataIndex: 'singleAmount',
      tip: '含税单件货值=（合计金额-税金）/入库数量--不含税单件货值=合计金额/入库数量',
      width: 80,
    },
    {
      title: '申购单号',
      dataIndex: 'planNo',
      width: 130,
    },
  ]
  const expandable = ref<any>({
    title: '',
    defaultExpandAllRows: true,
    expandedRowKeys: [],
    width: 10,
  })
  const tabsList = [
    { key: 10, title: '待签收' },
    { key: 30, title: '已签收' },
    { key: 20, title: '已拒收' },
  ]
  const rowSelection = ref({
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false,
  }) as any
  let searchVal = ref<any>({
    pageSize: 20,
    pageNum: 1,
    status: 10,
  })
  const currentTab = ref(10)
  const tableLoading = ref(false)
  const tableList = ref<Array<any>>([])
  const total = ref(0)
  const selectIds = ref<Array<string>>([])
  const currentData = ref<any>({})
  const showInStorageDetail = ref(false)
  const showInStorageItemDetail = ref(false)
  const countMap = ref<any>({})
  const filterData = ref<any>({})
  const tableListref = ref()
  const useBaseData = useBaseDataStore()

  // 显示sku规格
  function getProductSpecs(item: any) {
    let productSpecs = item.productSpecs ? parseJson(item.productSpecs, []) : []
    return productSpecs.map((el: any) => el.valueCn)?.join('*') || '--'
  }
  // 获取所有用户列表
  async function getUserList() {
    await useBaseData.getUserList()
    filterItem.value[3].optionItems = useBaseData.userList.map((el: any) => {
      return {
        label: el.userName,
        value: el.id,
      }
    })
  }
  // 获取仓库列表
  async function getWareHouseList() {
    const res: any = await findSaasAndErpWarehouse()
    let list = res?.data || []
    filterItem.value[2].optionItems = list.map((el: any) => {
      return {
        label: el.warehouseName,
        value: el.warehouseCode,
      }
    })
  }
  // 获取所有部门列表
  async function getDeptList() {
    await useBaseData.getDeptList()
    filterItem.value[5].optionItems = useBaseData.deptList
  }

  // 通过条件查询列表
  function searchByVal(info: any) {
    searchVal.value.pageNum = 1
    filterData.value = JSON.parse(JSON.stringify(info)) || {}
    getTableList()
  }
  // 分页
  function changePage(val: number) {
    searchVal.value.pageNum = val
    getTableList()
  }
  function sizeChange(val: number) {
    searchVal.value.pageSize = val
    getTableList()
  }
  function selectColumn(val: any) {
    selectIds.value = val
  }
  // 切换状态
  function changeStatus(status: number | string) {
    searchVal.value.status = status
    searchVal.value.pageNum = 1
    getTableList()
  }

  // 查询列表和数量合计
  function getListAndCount() {
    getTableList()
    getCountList()
  }
  // 查询各状态下数量合计
  async function getCountList() {
    const res: any = await findReceiptCountStatus()
    let counts = res?.data || []
    countMap.value = {}
    counts.forEach((el: any) => {
      countMap.value[el.status] = el.totalCount
    })
  }
  // 获取商品列表
  async function getTableList() {
    let params = {
      ...searchVal.value,
      ...filterData.value,
    }
    tableLoading.value = true
    const res: any = await findReceiptPage(params)
    tableListref.value.selectAll(false)
    tableLoading.value = false
    let list = res?.data?.records || []
    list.forEach((el: any) => {
      el.billItems.forEach((item: any) => {
        let purchaseSpecs = item.purchaseSpecs ? parseJson(item.purchaseSpecs, {}) : {}
        item.purchaseSpecsArr = Object.values(purchaseSpecs)
      })
    })
    tableList.value = list
    total.value = res?.data?.total || 0
    expandable.value.expandedRowKeys = tableList.value.map((el: any) => el.id)
  }
  // 合并单元格
  function spanMethodAll(option: any) {
    let { column } = option
    if (column.dataIndex === 'img') {
      return { rowspan: 1, colspan: 21 }
    }
  }

  // 入库单详情
  function openInStorageDetail(row: any) {
    currentData.value = row
    showInStorageDetail.value = true
  }
  // 入库单明细详情
  function openInStorageItemDetail(row: any, parentInfo: any) {
    currentData.value = row
    currentData.value.billNo = parentInfo.billNo
    showInStorageItemDetail.value = true
  }
</script>
<style lang="less" scoped>
  :deep(.arco-table-td) {
    background-color: var(--color-fill-1);
    height: auto;
  }
  :deep(.arco-table-tr-expand) {
    .arco-table-cell {
      padding: 0;
    }
    .arco-table {
      margin: 0 !important;
      .arco-table-td {
        border-bottom: 1px solid var(--color-neutral-3) !important;
        height: 48px;
      }
    }
    background-color: #fff !important;
  }
  :deep(.child-row) {
    .arco-table-cell {
      padding: 2px 8px;
    }
  }
  :deep(.arco-table-tr-expand .arco-table-td) {
    background-color: #fff !important;
    border-bottom: none;
  }
  :deep(.arco-table-tr-expand tr:hover .arco-table-td) {
    background-color: var(--color-fill-1) !important;
  }
  :deep(.arco-table-expand .arco-table-cell) {
    display: none;
  }
  :deep(.arco-tabs-nav-tab) {
    background-color: #fff;
  }
  .price-type {
    font-size: 12px;
    transform: scale(0.82);
    position: relative;
    left: -4px;
  }
  .order-w {
    padding: 5px 0;
    color: #666;
    flex: 1;
    .order-detail-item {
      width: 200px;
      padding-right: 5px;
    }
  }
</style>
